package com.maoxs;

import com.maoxs.pojo.Result;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@Slf4j
public class LoginController {
    @RequestMapping(value = "/")
    public String index() {
        return "main";
    }


    @RequestMapping(value = "/login")
    public String main() {
        return "index";
    }


    @RequestMapping(value = "/login", method = RequestMethod.POST)
    @ResponseBody
    public Result login(@RequestParam("username") String userName, @RequestParam("password") String Password) throws Exception {
        Subject currentUser = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(userName, Password);
        token.setRememberMe(true);// 默认不记住密码
        try {
            currentUser.login(token); //登录
            log.info("==========登录成功=======");
            return new Result(true, "登录成功");

        } catch (UnknownAccountException e) {
            log.info("==========用户名不存在=======");
            return new Result(false, "用户名不存在");
        } catch (DisabledAccountException e) {
            log.info("==========您的账户已经被冻结=======");
            return new Result(false, "您的账户已经被冻结");
        } catch (IncorrectCredentialsException e) {
            log.info("==========密码错误=======");
            return new Result(false, "密码错误");
        } catch (ExcessiveAttemptsException e) {
            log.info("==========您错误的次数太多了吧,封你半小时=======");
            return new Result(false, "您错误的次数太多了吧,封你半小时");
        } catch (RuntimeException e) {
            log.info("==========运行异常=======");
            return new Result(false, "运行异常");
        }
    }


    @RequestMapping("/logout")
    public String logOut() {
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return "index";
    }

}
